//
//  MBProgressHUD+ZXCategory.m
//  YiShangbao
//
//  Created by simon on 17/6/22.
//  Copyright © 2017年 com.Microants. All rights reserved.
//

#import "MBProgressHUD+ZXCategory.h"


#ifndef UIColorFromRGB_HexValue
#define UIColorFromRGB_HexValue(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0f blue:((float)(rgbValue & 0xFF))/255.0f alpha:1.f]
#endif


@implementation MBProgressHUD (ZXCategory)

#pragma mark - ShowLoading

+ (void)zx_showLoading{
    
    [self zx_showLoadingWithStatus:nil];
}


+ (void)zx_showLoadingWithStatus:(nullable NSString *)text{
    [self zx_showLoadingWithStatus:text toView:nil];
}


+ (void)zx_showLoadingWithStatus:(nullable NSString *)text toView:(nullable UIView *)view{
    if ([NSThread isMainThread]) {
        [MBProgressHUD zx_safeShowLoadingWithStatus:text toView:view];
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD zx_safeShowLoadingWithStatus:text toView:view];
        });
    }
}

+ (void)zx_safeShowLoadingWithStatus:(nullable NSString *)text toView:(nullable UIView *)view
{
    if (!view)
    {
        view = [MBProgressHUD getFrontWindow];
    }
    MBProgressHUD *hud = [MBProgressHUD HUDForView:view];
    if (!hud)
    {
        hud = [[MBProgressHUD alloc] initWithView:view];
        hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
        hud.bezelView.color = [UIColor colorWithWhite:0 alpha:0.75f];
        hud.contentColor = UIColorFromRGB_HexValue(0xffffff);
        ///显示HUD的宽限时间
        hud.graceTime = 0.1;
        hud.removeFromSuperViewOnHide = YES;
        [view addSubview:hud];
        [hud showAnimated:YES];
    }
    hud.label.text= NSLocalizedString(text, nil);
}


#pragma mark - ShowSuccess

+ (void)zx_showSuccess:(nullable NSString *)success{
    [self zx_showSuccess:success toView:nil hideAfterDelay:0 completionBlock:nil];
}

+ (void)zx_showSuccess:(nullable NSString *)success toView:(nullable UIView *)view
{
    [self zx_showSuccess:success toView:view hideAfterDelay:0 completionBlock:nil];
}

+ (void)zx_showSuccess:(nullable NSString *)success
                toView:(nullable UIView *)view
       completionBlock:(nullable MBProgressHUDCompletionBlock)completionBlock
{
    [self zx_showSuccess:success toView:view hideAfterDelay:0 completionBlock:completionBlock];
}

+ (void)zx_showSuccess:(nullable NSString *)success
                toView:(nullable UIView *)view
        hideAfterDelay:(NSTimeInterval)delay
{
    [self zx_showSuccess:success toView:view hideAfterDelay:delay completionBlock:nil];
}

+ (void)zx_showSuccess:(nullable NSString *)success
                toView:(nullable UIView *)view
        hideAfterDelay:(NSTimeInterval)delay
       completionBlock:(nullable MBProgressHUDCompletionBlock)completionBlock
{
    [MBProgressHUD zx_showText:success customIcon:nil view:view hideAfterDelay:delay completionBlock:completionBlock];
}



#pragma mark - ShowError
+ (void)zx_showError:(nullable NSString *)error{
    [MBProgressHUD zx_showError:error toView:nil];
}

+ (void)zx_showError:(nullable NSString *)error toView:(nullable UIView *)view
{
    [MBProgressHUD zx_showError:error toView:view hideAfterDelay:0 completionBlock:nil];
}

+ (void)zx_showError:(nullable NSString *)error
              toView:(nullable UIView *)view
     completionBlock:(nullable MBProgressHUDCompletionBlock)completionBlock
{
    [MBProgressHUD zx_showError:error toView:view hideAfterDelay:0 completionBlock:completionBlock];
}


+ (void)zx_showError:(nullable NSString *)error
              toView:(nullable UIView *)view
      hideAfterDelay:(NSTimeInterval)delay
{
    [MBProgressHUD zx_showError:error toView:view hideAfterDelay:delay completionBlock:nil];
}


+ (void)zx_showError:(nullable NSString *)error
              toView:(nullable UIView *)view
      hideAfterDelay:(NSTimeInterval)delay
     completionBlock:(nullable MBProgressHUDCompletionBlock)completionBlock
{
    [MBProgressHUD zx_showText:error customIcon:nil view:view hideAfterDelay:0 completionBlock:completionBlock];
}





#pragma mark - ShowText基础方法

+ (void)zx_showText:(nullable NSString *)text
         customIcon:(nullable UIImage *)iconImage
               view:(nullable UIView *)view
     hideAfterDelay:(NSTimeInterval)delay
    completionBlock:(nullable MBProgressHUDCompletionBlock)completionBlock
{
    if ([NSThread isMainThread]) {
        [MBProgressHUD zx_safeShowText:text customIcon:iconImage view:view hideAfterDelay:delay completionBlock:completionBlock];
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
          [MBProgressHUD zx_safeShowText:text customIcon:iconImage view:view hideAfterDelay:delay completionBlock:completionBlock];
        });
    }
}

+ (MBProgressHUD *)zx_safeShowText:(nullable NSString *)text
                        customIcon:(nullable UIImage *)iconImage
                              view:(nullable UIView *)view
                    hideAfterDelay:(NSTimeInterval)delay
                   completionBlock:(MBProgressHUDCompletionBlock)completionBlock
{
    if (!view)
    {
        view = [MBProgressHUD getFrontWindow];
    }
    [MBProgressHUD hideHUDForView:view animated:NO];
    

    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    //默认白色
    hud.contentColor = [UIColor whiteColor];
    hud.opaque = YES;
    hud.backgroundColor = [UIColor clearColor];
    ///默认是模糊样式
    hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.bezelView.color = [UIColor colorWithWhite:0 alpha:0.75f];
    //默认如此
    hud.backgroundView.backgroundColor = [UIColor clearColor];
    NSTimeInterval time = delay;
    ///支持配置多行展示
    if (text.length>12)
    {
//        hud.detailsLabel.text= text;
//        hud.detailsLabel.font = [UIFont systemFontOfSize:16];
        hud.label.text= text;
        hud.label.numberOfLines = 0;
    }
    else
    {
        hud.label.text= text;
    }
    if (iconImage)
    {
        hud.mode = MBProgressHUDModeCustomView;
        hud.customView = [[UIImageView alloc] initWithImage:iconImage];
        //放图片时去背景色
        hud.bezelView.color = [UIColor clearColor];
    }
    else
    {
        hud.mode = MBProgressHUDModeText;
    }
    hud.completionBlock = ^{
        if (completionBlock) {
            completionBlock();
        }
    };
    ///最小显示持续时间,默认0；
    hud.minShowTime = 1.5;
    //支持toast展示时间，根据文本长度动态计算。再配置最小显示持续时间1.5s；再限制最大展示时间6s；
    time = delay>0?delay:(1.f+text.length*0.05);
    NSTimeInterval minDelayTime = MIN(time, 6);
    [hud hideAnimated:YES afterDelay:minDelayTime];
    return hud;
}

#pragma mark - hideHUD


+ (void)zx_hideHUD{
    [self zx_hideHUDForView:nil];
}

+ (void)zx_hideHUDForView:(nullable UIView *)view
{
    if ([NSThread isMainThread]) {
        [MBProgressHUD zx_safeHideHUDForView:view];
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD zx_safeHideHUDForView:view];
            
        });
    }
}

+ (BOOL)zx_safeHideHUDForView:(nullable UIView *)view
{
    if (!view)
    {
        view = [MBProgressHUD getFrontWindow];
    }
   return [MBProgressHUD hideHUDForView:view animated:NO];
}



#pragma mark - 其它

///新增最前面的window是否是指定4个；
///一般情况下，windows数组的最后一个就是最上面的window。
+ (nullable UIWindow *)getFrontWindow
{
    NSEnumerator *frontToBackWindows = [[self getWindows] reverseObjectEnumerator];
    for (UIWindow *window in frontToBackWindows)
    {
        BOOL windowIsVisible = !window.hidden && window.alpha > 0;
        BOOL windowLevelSupported = (window.windowLevel >= UIWindowLevelNormal);
        ///需要iPad多屏上测试是否有影响，iPhone上可行
        NSString *windowClass =  [[window class] description];
        BOOL systemWindow = [windowClass isEqualToString:@"UIWindow"]
        ||[windowClass isEqualToString:@"UITextEffectsWindow"]
        ||[windowClass isEqualToString:@"UIRemoteKeyboardWindow"]
        ||[windowClass isEqualToString:@"_UIInteractiveHighlightEffectWindow"];
        if(windowIsVisible && windowLevelSupported && systemWindow) {
            return window;
            break;
        }
    }
    return nil;
}

+ (NSArray *)getWindows
{
    NSArray *windows = nil;
    if (@available(iOS 13.0,*)) {
        NSSet <UIScene *>*connectedScenes = [UIApplication sharedApplication].connectedScenes;
        UIWindowScene *scene = nil;
        if (![UIApplication sharedApplication].supportsMultipleScenes) {
            scene = (UIWindowScene *)[[connectedScenes allObjects] firstObject];
        }else{
            for (UIWindowScene * windowScene in connectedScenes) {
                if (windowScene.activationState == UISceneActivationStateForegroundActive) {
                    scene = windowScene;
                }
            }
        }
        windows = scene.windows;
    }else{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        windows = UIApplication.sharedApplication.windows;
#pragma clang diagnostic pop
    }
    return windows;
}




/*
//@"litteMoney"
+ (void)zx_showGifWithGifName:(NSString *)gifName toView:(nullable UIView *)view
{
    if (!view)
    {
        view = [MBProgressHUD getFrontWindow];
    }
    UIImage *image = [UIImage zx_animatedGIFNamed:gifName];
    UIImageView *gifView = [[UIImageView alloc]initWithFrame:CGRectMake(0,0,image.size.width/2, image.size.height/2)];
    gifView.image = image;
    MBProgressHUD *hud = [MBProgressHUD HUDForView:view];
    if (!hud)
    {
        hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    }
    //    hud.bezelView.backgroundColor = [UIColor clearColor];
    //    hud.backgroundView.backgroundColor =[UIColor clearColor];
    hud.square = NO;
    hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.bezelView.color = [UIColor clearColor];
    hud.mode = MBProgressHUDModeCustomView;
    hud.customView = gifView;
}

//自定义加载动画
+ (void)zx_showGifWithGifName:(NSString *)gifName Text:(nullable NSString *)aText toView:(nullable UIView *)view{
    [MBProgressHUD zx_showGifWithGifName:gifName Text:aText time:0 toView:view];
}

//自定义加载动画 显示时间
+ (void)zx_showGifWithGifName:(NSString *)gifName Text:(nullable NSString *)aText time:(CGFloat)time toView:(nullable UIView *)view{
    if (!view)
    {
        view = [MBProgressHUD getFrontWindow];
    }
    UIImage *image = [UIImage zx_animatedGIFNamed:gifName];
    UIImageView *gifView = [[UIImageView alloc]initWithFrame:CGRectMake(0,0,image.size.width/2, image.size.height/2)];
    gifView.image = image;
    MBProgressHUD *hud = [MBProgressHUD HUDForView:view];
    if (!hud){
        hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    }
    
    if (aText.length>12){
        hud.detailsLabel.text= NSLocalizedString(aText, nil);
        hud.detailsLabel.font = [UIFont systemFontOfSize:15];
    }else{
        hud.label.text= NSLocalizedString(aText, nil);
    }
    hud.square = NO;
    hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.bezelView.color = [UIColor colorWithWhite:0 alpha:0.5f];
    hud.mode = MBProgressHUDModeCustomView;
    hud.customView = gifView;
    if (time){
        [hud hideAnimated:YES afterDelay:time];
    }
}





//
+ (void)jl_showGifWithGifName:(NSString *)gifName imagesCount:(NSInteger )imgCount toView:(nullable UIView *)view
{
    if (!view)
    {
        view = [MBProgressHUD getFrontWindow];
    }
    
    NSMutableArray *arrayM = [NSMutableArray array];
    for (int i=1; i<=imgCount; ++i) {
        NSString *strImg = [NSString stringWithFormat:@"%@%d",gifName,i];
        UIImage *image = [UIImage imageNamed:strImg];
        if (image) {
            [arrayM addObject:image];
        }
    }
    UIImage *image = arrayM.firstObject;
    UIImageView *gifView = [[UIImageView alloc]initWithFrame:CGRectMake(0,0,image.size.width/2, image.size.height/2)];
    gifView.animationImages = arrayM;
    gifView.animationDuration = 0.05*arrayM.count;
    gifView.animationRepeatCount = 0;//播放次数（一直循环播放）
    [gifView startAnimating];//开始播放
    
    MBProgressHUD *hud = [MBProgressHUD HUDForView:view];
    if (!hud)
    {
        hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    }
    hud.square = NO;
    hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.bezelView.color = [UIColor clearColor];
    hud.mode = MBProgressHUDModeCustomView;
    hud.customView = gifView;
}
*/


@end
